package cn.semes.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 1.获取请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        // 如果请求包含login，或者rigister允许进入run方法
        if(uri.endsWith("login")||uri.endsWith("rigister")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取请求投
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 获取响应头
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        // 设置编码和数据格式
        response.setContentType("application/josn;charset=utf-8");
        // 获取请求头中的token
        String token = request.getHeader("token");
        // 判断token是否为空
        if(!StringUtils.hasLength(token)){
            // 设置响应内容
            try {
                // 1.设置响应内容
                PrintWriter writer = response.getWriter();
                HashMap<String, Object> map = new HashMap<>();
                map.put("success", false);
                map.put("message", "登录校验失败，请重新登录！");
                String data = JSON.toJSONString(map);
                writer.write(data);
                // 2.阻止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
